<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>登录/注册</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
            padding: 40px 30px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .header h1 {
            color: #333;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 10px;
        }

        .header p {
            color: #666;
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            color: #333;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 8px;
        }

        .form-group.inline-label .label-input-group {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .form-group.inline-label label {
            margin-bottom: 0;
            min-width: 80px;
        }

        .input-wrapper {
            position: relative;
        }

        .form-group input {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            background: white;
        }

        .form-group input.error {
            border-color: #e74c3c;
        }

        .form-group input.success {
            border-color: #27ae60;
        }

        .verification-group {
            display: flex;
            gap: 10px;
        }

        .verification-group input {
            flex: 1;
        }

        .btn-send {
            background: #667eea;
            color: white;
            border: none;
            padding: 15px 20px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
            min-width: 120px;
        }

        .btn-send:hover {
            background: #5a6fd8;
        }

        .btn-send:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
        }

        .btn-submit {
            width: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 18px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 30px;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-submit:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .error-message {
            color: #e74c3c;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }

        .success-message {
            color: #27ae60;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }

        .loading {
            display: none;
            text-align: center;
            margin-top: 20px;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .terms {
            margin-top: 20px;
            text-align: center;
            font-size: 12px;
            color: #666;
        }

        .terms a {
            color: #667eea;
            text-decoration: none;
        }

        .test-section {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 15px;
            border: 2px dashed #dee2e6;
        }

        .test-title {
            color: #495057;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 15px;
            text-align: center;
        }

        .btn-test {
            width: 100%;
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
            padding: 15px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 10px;
        }

        .btn-test:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(40, 167, 69, 0.3);
        }

        .test-info {
            text-align: center;
            color: #6c757d;
            font-size: 12px;
            line-height: 1.4;
        }

        .phone-display {
            background: #f8f9fa;
            padding: 10px 15px;
            border-radius: 8px;
            font-size: 14px;
            color: #666;
            margin-bottom: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>登录/注册</h1>
            <p>输入手机号并完成验证</p>
        </div>

        <form id="registerForm">
            <!-- <div class="form-group inline-label">
                <div class="label-input-group">
                    <label for="wxopenid">微信OpenID</label>
                    <div class="input-wrapper">
                        <input 
                            type="text" 
                            id="wxopenid" 
                            name="wxopenid" 
                            placeholder="请输入微信OpenID" 
                            readonly
                            autocomplete="off"
                        >
                    </div>
                </div>
                <div class="error-message" id="wxopenidError"></div>
                <div class="success-message" id="wxopenidSuccess"></div>
            </div> -->

            <div class="form-group inline-label">
                <div class="label-input-group">
                    <label for="name">姓名</label>
                    <div class="input-wrapper">
                        <input 
                            type="text" 
                            id="name" 
                            name="name" 
                            placeholder="请输入您的姓名" 
                            maxlength="20"
                            autocomplete="name"
                        >
                    </div>
                </div>
                <div class="error-message" id="nameError"></div>
                <div class="success-message" id="nameSuccess"></div>
            </div>

            <div class="form-group inline-label">
                <div class="label-input-group">
                    <label for="company">公司全名</label>
                    <div class="input-wrapper">
                        <input 
                            type="text" 
                            id="company" 
                            name="company" 
                            placeholder="请输入公司全名" 
                            maxlength="50"
                            autocomplete="organization"
                        >
                    </div>
                </div>
                <div class="error-message" id="companyError"></div>
                <div class="success-message" id="companySuccess"></div>
            </div>

            <div class="form-group inline-label">
                <div class="label-input-group">
                    <label for="phone">手机号码</label>
                    <div class="input-wrapper">
                        <input 
                            type="tel" 
                            id="phone" 
                            name="phone" 
                            placeholder="请输入手机号码" 
                            maxlength="11"
                            autocomplete="tel"
                        >
                    </div>
                </div>
                <div class="error-message" id="phoneError"></div>
                <div class="success-message" id="phoneSuccess"></div>
            </div>

            <div class="form-group" id="verificationSection">
                <label for="verificationCode">验证码</label>
                <div class="verification-group">
                    <input 
                        type="text" 
                        id="verificationCode" 
                        name="code" 
                        placeholder="请输入6位验证码" 
                        maxlength="6"
                        autocomplete="one-time-code"
                    >
                    <button type="button" class="btn-send" id="sendCodeBtn">获取验证码</button>
                </div>
                <div class="error-message" id="codeError"></div>
                <div class="success-message" id="codeSuccess"></div>
            </div>

            <div class="phone-display" id="phoneDisplay" style="display: none;"></div>

            <button type="submit" class="btn-submit" id="submitBtn" disabled>注册</button>
        </form>

        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p style="margin-top: 10px; color: #666;">处理中...</p>
        </div>

        <div class="terms">
            <p>注册即表示同意 <a href="#">用户协议</a> 和 <a href="#">隐私政策</a></p>
        </div>

        <div class="test-section">
            <div class="test-title">🧪 测试功能</div>
            <button class="btn-test" onclick="testRedirectToProfile()">
                跳转到个人中心
            </button>
            <button class="btn-test" onclick="goToProfile()">
                进入个人中心
            </button>
            <button class="btn-test" onclick="debugParams()">
                调试参数
            </button>
            <div class="test-info">
                点击按钮可跳转到对应页面进行测试<br>
                当前buserid: <span id="currentBuyerId">未设置</span>
            </div>
        </div>
    </div>

    <!-- 认证系统 -->
    <script src="auth.js"></script>
    <script src="api.js"></script>
    <script src="router.js"></script>
    
    <script>
        class PhoneRegister {
            constructor() {
                this.form = document.getElementById('registerForm');
                this.phoneInput = document.getElementById('phone');
                this.verificationInput = document.getElementById('verificationCode');
                this.sendCodeBtn = document.getElementById('sendCodeBtn');
                this.submitBtn = document.getElementById('submitBtn');
                this.verificationSection = document.getElementById('verificationSection');
                this.phoneDisplay = document.getElementById('phoneDisplay');
                this.loading = document.getElementById('loading');
                
                // 调试：检查按钮是否正确获取
                console.log('🔍 按钮元素检查:');
                console.log('- sendCodeBtn:', this.sendCodeBtn);
                console.log('- sendCodeBtn.id:', this.sendCodeBtn ? this.sendCodeBtn.id : 'null');
                console.log('- sendCodeBtn.textContent:', this.sendCodeBtn ? this.sendCodeBtn.textContent : 'null');
                
                this.countdown = 60;
                this.timer = null;
                this.apiBaseUrl = 'http://api.dadefeng.com'; // API基础路径
                this.storedOpenid = null; // 存储获取到的openid
                this.buyerId = null; // 存储从URL参数解析的buyerid
                this.flag = null; // 存储从URL参数解析的flag
                
                this.init();
            }

            init() {
                console.log('🚀 PhoneRegister init() 方法开始执行');
                
                this.phoneInput.addEventListener('input', this.handlePhoneInput.bind(this));
                this.verificationInput.addEventListener('input', this.handleCodeInput.bind(this));
                
                // 绑定获取验证码按钮事件
                this.sendCodeBtn.addEventListener('click', (e) => {
                    console.log('🔘 获取验证码按钮被点击！');
                    e.preventDefault();
                    e.stopPropagation();
                    
                    console.log('🔘 调用 sendVerificationCodeNew 方法');
                    this.sendVerificationCodeNew(e);
                    return false;
                });
                
                this.form.addEventListener('submit', (e) => {
                    console.log('📝 表单提交事件触发');
                    e.preventDefault();
                    
                    // 检查是否是注册按钮触发的提交
                    if (e.submitter && e.submitter.id === 'submitBtn') {
                        console.log('📝 通过注册按钮提交表单');
                        this.handleSubmitNew(e);
                    } else {
                        console.log('📝 非注册按钮触发，阻止提交');
                    }
                    return false;
                });
                
                // 添加姓名和公司字段验证
                const nameInput = document.getElementById('name');
                const companyInput = document.getElementById('company');
                nameInput.addEventListener('input', this.handleNameInput.bind(this));
                companyInput.addEventListener('input', this.handleCompanyInput.bind(this));
                
                console.log('📍 当前页面URL:', window.location.href);
                console.log('📍 当前页面搜索参数:', window.location.search);
                
                // 解析URL参数获取buyerid和openid
                console.log('🔍 开始解析URL参数...');
                this.parseUrlParams();
                console.log('✅ URL参数解析完成');
                
                console.log('📋 解析后的参数状态:');
                console.log('- flag:', this.flag);
                console.log('- buyerId:', this.buyerId);
                console.log('- storedOpenid:', this.storedOpenid);
                
                // 检查flag参数，如果flag=Y且已经注册过才跳转，否则保持在登录页面
                if (this.flag === 'Y') {
                    console.log('🎯 检测到flag=Y，但保持在登录页面等待用户操作');
                    // 临时禁用自动跳转，让用户可以手动获取验证码
                    // this.immediateRedirectToHome();
                    this.showLoginWelcomeMessage();
                } else {
                    console.log('📝 flag不是Y（当前值：' + this.flag + '），保持在登录页面');
                    // flag=N或其他值时，保持在登录页面，显示相应的欢迎信息
                    this.showLoginWelcomeMessage();
                }
                
                console.log('🏁 PhoneRegister init() 方法执行完成');
            }
            
            // 直接跳转到首页（注册成功后使用）
            immediateRedirectToHome() {
                console.log('🚀🚀🚀 immediateRedirectToHome() 方法被调用！🚀🚀🚀');
                
                // 调试：检查当前存储的参数
                console.log('📋 当前存储的参数:');
                console.log('- storedOpenid:', this.storedOpenid);
                console.log('- buyerId:', this.buyerId);
                console.log('- flag:', this.flag);
                
                const homeUrl = 'home.html';
                const params = new URLSearchParams();
                
                // 添加相关参数
                if (this.buyerId) {
                    params.append('buserid', this.buyerId);
                    console.log('✅ 添加buserid参数:', this.buyerId);
                }
                
                if (this.storedOpenid) {
                    params.append('muserid', this.storedOpenid);
                    console.log('✅ 添加muserid参数:', this.storedOpenid);
                }
                
                if (this.flag) {
                    params.append('flag', this.flag);
                    console.log('✅ 添加flag参数:', this.flag);
                }
                
                const fullUrl = `${homeUrl}?${params.toString()}`;
                
                console.log('🎯🎯🎯 即将跳转到以下URL：🎯🎯🎯');
                console.log('完整URL:', fullUrl);
                
                // 显示快速跳转提示
                this.showImmediateRedirectMessage(fullUrl);
                
                // 立即跳转（500ms延迟让用户看到提示）
                setTimeout(() => {
                    console.log('🚀🚀🚀 执行跳转... 🚀🚀🚀');
                    try {
                        console.log('✅ 使用 window.location.href 跳转');
                        window.location.href = fullUrl;
                    } catch (error) {
                        console.error('❌ 跳转失败:', error);
                        window.open(fullUrl, '_self');
                    }
                }, 500);
            }

            // 直接跳转到个人中心（当flag=Y时使用）
            immediateRedirectToProfile() {
                console.log('🚀🚀🚀 immediateRedirectToProfile() 方法被调用！🚀🚀🚀');
                
                // 调试：检查当前存储的参数
                console.log('📋 当前存储的参数:');
                console.log('- storedOpenid:', this.storedOpenid);
                console.log('- buyerId:', this.buyerId);
                console.log('- flag:', this.flag);
                
                // 验证flag值
                if (this.flag !== 'Y') {
                    console.log('❌ 警告：flag值不是Y，当前值：', this.flag);
                }
                
                const profileUrl = 'profile.html';
                const params = new URLSearchParams();
                
                // 只添加buserid参数（根据要求）
                if (this.buyerId) {
                    params.append('buserid', this.buyerId);
                    console.log('✅ 添加buserid参数:', this.buyerId);
                } else {
                    console.log('❌ buserid参数不存在，无法跳转');
                    return;
                }
                
                // 添加直接跳转标识
                params.append('immediate_redirect', 'true');
                params.append('timestamp', Date.now());
                
                const fullUrl = `${profileUrl}?${params.toString()}`;
                
                console.log('🎯🎯🎯 即将跳转到以下URL：🎯🎯🎯');
                console.log('完整URL:', fullUrl);
                console.log('🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯');
                
                // 验证URL格式
                if (!fullUrl.startsWith('profile.html')) {
                    console.log('❌ 错误：URL格式不正确，应该以profile.html开头');
                    console.log('实际URL:', fullUrl);
                    return;
                }
                
                // 显示快速跳转提示
                this.showImmediateRedirectMessage(fullUrl);
                
                // 立即跳转（500ms延迟让用户看到提示）
                setTimeout(() => {
                    console.log('🚀🚀🚀 执行跳转... 🚀🚀🚀');
                    console.log('目标URL:', fullUrl);
                    console.log('当前URL:', window.location.href);
                    
                    try {
                        console.log('✅ 使用 window.location.href 跳转');
                        window.location.href = fullUrl;
                    } catch (error) {
                        console.error('❌ 跳转失败:', error);
                        console.log('🔄 尝试使用 window.open 跳转');
                        window.open(fullUrl, '_self');
                    }
                }, 500);
            }

            // 显示快速跳转提示
            showImmediateRedirectMessage(url) {
                try {
                    const container = document.querySelector('.container');
                    if (!container) {
                        console.error('找不到容器元素');
                        return;
                    }
                    
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'immediate-redirect-message';
                    messageDiv.innerHTML = `
                        <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; margin-bottom: 20px; color: white;">
                            <div style="font-size: 18px; font-weight: 600; margin-bottom: 10px;">
                                🎯 检测到登录状态
                            </div>
                            <div style="font-size: 14px; margin-bottom: 15px; opacity: 0.9;">
                                正在快速跳转到个人中心...
                            </div>
                            <div style="font-size: 12px; margin-bottom: 10px; opacity: 0.8; word-break: break-all;">
                                ${url}
                            </div>
                            <div style="font-size: 11px; opacity: 0.7; font-style: italic;">
                                仅传递buserid参数用于获取公司信息
                            </div>
                            <div style="margin-top: 15px;">
                                <div class="spinner" style="border-color: white; border-top-color: transparent; width: 20px; height: 20px; margin: 0 auto;"></div>
                            </div>
                        </div>
                    `;
                    
                    // 插入到header后面
                    const header = container.querySelector('.header');
                    if (header) {
                        header.insertAdjacentElement('afterend', messageDiv);
                    } else {
                        container.insertBefore(messageDiv, container.firstChild);
                    }
                    
                    // 隐藏其他内容
                    const form = document.getElementById('registerForm');
                    const terms = document.querySelector('.terms');
                    const testSection = document.querySelector('.test-section');
                    if (form) form.style.display = 'none';
                    if (terms) terms.style.display = 'none';
                    if (testSection) testSection.style.display = 'none';
                    
                    console.log('快速跳转提示显示成功');
                } catch (error) {
                    console.error('显示快速跳转提示失败:', error);
                }
            }

            // 默认跳转到个人中心
            defaultRedirectToProfile() {
                console.log('执行默认跳转到个人中心');
                
                // 调试：检查当前存储的参数
                console.log('当前存储的参数:');
                console.log('- storedOpenid:', this.storedOpenid);
                console.log('- buyerId:', this.buyerId);
                console.log('- flag:', this.flag);
                
                const profileUrl = 'profile.html';
                const params = new URLSearchParams();
                
                // 添加当前存储的参数
                if (this.storedOpenid) {
                    params.append('muserid', this.storedOpenid);
                    console.log('添加muserid参数:', this.storedOpenid);
                }
                if (this.buyerId) {
                    params.append('buserid', this.buyerId);
                    console.log('添加buserid参数:', this.buyerId);
                }
                if (this.flag) {
                    params.append('flag', this.flag);
                    console.log('添加flag参数:', this.flag);
                }
                
                // 添加默认跳转标识
                params.append('auto_redirect', 'true');
                params.append('timestamp', Date.now());
                
                const fullUrl = `${profileUrl}?${params.toString()}`;
                
                console.log('=== 最终跳转URL ===');
                console.log('默认跳转URL:', fullUrl);
                console.log('====================');
                
                // 显示跳转提示
                this.showDefaultRedirectMessage();
                
                // 延迟跳转，让用户看到提示
                setTimeout(() => {
                    console.log('🚀 开始执行跳转...');
                    console.log('📋 目标URL:', fullUrl);
                    console.log('📍 当前页面URL:', window.location.href);
                    
                    try {
                        console.log('✅ 使用 window.location.href 跳转');
                        window.location.href = fullUrl;
                    } catch (error) {
                        console.error('❌ 跳转失败:', error);
                        console.log('🔄 尝试使用 window.open 跳转');
                        window.open(fullUrl, '_self');
                    }
                }, 2000);
            }

            // 显示默认跳转提示
            showDefaultRedirectMessage() {
                try {
                    const container = document.querySelector('.container');
                    if (!container) {
                        console.error('找不到容器元素');
                        return;
                    }
                    
                    // 构建跳转URL用于显示
                    const profileUrl = 'profile.html';
                    const params = new URLSearchParams();
                    
                    // 添加当前存储的参数
                    if (this.storedOpenid) {
                        params.append('muserid', this.storedOpenid);
                    }
                    if (this.buyerId) {
                        params.append('buserid', this.buyerId);
                    }
                    if (this.flag) {
                        params.append('flag', this.flag);
                    }
                    
                    // 添加默认跳转标识
                    params.append('auto_redirect', 'true');
                    params.append('timestamp', Date.now());
                    
                    const fullUrl = `${profileUrl}?${params.toString()}`;
                    
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'default-redirect-message';
                    messageDiv.innerHTML = `
                        <div style="text-align: center; padding: 30px 20px; background: linear-gradient(135deg, #e8f5e8 0%, #d4edda 100%); border-radius: 15px; margin-bottom: 20px;">
                            <div style="color: #155724; font-size: 20px; font-weight: 600; margin-bottom: 12px;">
                                🎉 欢迎访问
                            </div>
                            <div style="color: #155724; font-size: 16px; margin-bottom: 15px;">
                                正在为您跳转到个人中心...
                            </div>
                            <div style="color: #666; font-size: 14px; margin-bottom: 20px;">
                                ${this.buyerId ? `买家ID: ${this.buyerId}` : ''}
                            </div>
                            <div style="color: #007bff; font-size: 12px; margin-bottom: 15px; word-break: break-all;">
                                跳转地址: ${fullUrl}
                            </div>
                            <div style="margin-top: 20px;">
                                <div class="spinner" style="border-color: #27ae60; border-top-color: transparent; width: 30px; height: 30px; margin: 0 auto;"></div>
                            </div>
                            <div style="margin-top: 20px;">
                                <button onclick="cancelRedirect()" style="background: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; cursor: pointer; margin-right: 10px;">
                                    取消跳转
                                </button>
                                <button onclick="forceRedirect()" style="background: #28a745; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; cursor: pointer;">
                                    立即跳转
                                </button>
                            </div>
                        </div>
                    `;
                    
                    // 插入到header后面
                    const header = container.querySelector('.header');
                    if (header) {
                        header.insertAdjacentElement('afterend', messageDiv);
                    } else {
                        container.insertBefore(messageDiv, container.firstChild);
                    }
                    
                    // 隐藏注册表单和测试区域
                    const form = document.getElementById('registerForm');
                    const terms = document.querySelector('.terms');
                    const testSection = document.querySelector('.test-section');
                    if (form) form.style.display = 'none';
                    if (terms) terms.style.display = 'none';
                    if (testSection) testSection.style.display = 'none';
                    
                    console.log('默认跳转消息显示成功');
                } catch (error) {
                    console.error('显示默认跳转消息失败:', error);
                }
            }

            // 显示登录页面欢迎信息（当flag=N时使用）
            showLoginWelcomeMessage() {
                try {
                    console.log('🏠 显示登录页面欢迎信息');
                    
                    const container = document.querySelector('.container');
                    if (!container) {
                        console.error('找不到容器元素');
                        return;
                    }
                    
                    // 根据flag值显示不同的欢迎信息
                    let welcomeTitle = '欢迎访问';
                    let welcomeMessage = '请完成注册以继续';
                    let messageColor = '#667eea';
                    
                    if (this.flag === 'N') {
                        welcomeTitle = '欢迎回来';
                        welcomeMessage = '请登录您的账户';
                        messageColor = '#28a745';
                    }
                    
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'login-welcome-message';
                    messageDiv.innerHTML = `
                        <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, ${messageColor}88 0%, ${messageColor}cc 100%); border-radius: 15px; margin-bottom: 20px; color: white;">
                            <div style="font-size: 18px; font-weight: 600; margin-bottom: 10px;">
                                🎉 ${welcomeTitle}
                            </div>
                            <div style="font-size: 14px; margin-bottom: 15px; opacity: 0.9;">
                                ${welcomeMessage}
                            </div>
                            <div style="font-size: 12px; opacity: 0.8;">
                                ${this.buyerId ? `买家ID: ${this.buyerId}` : ''}
                                ${this.storedOpenid ? `微信ID: ${this.storedOpenid}` : ''}
                            </div>
                        </div>
                    `;
                    
                    // 插入到header后面
                    const header = container.querySelector('.header');
                    if (header) {
                        header.insertAdjacentElement('afterend', messageDiv);
                    } else {
                        container.insertBefore(messageDiv, container.firstChild);
                    }
                    
                    console.log('登录页面欢迎信息显示成功');
                } catch (error) {
                    console.error('显示登录页面欢迎信息失败:', error);
                }
            }

            // 显示自己邀请自己的错误提示
            showSelfInviteError() {
                try {
                    console.log('⚠️ 显示自己邀请自己错误提示');
                    
                    const container = document.querySelector('.container');
                    if (!container) {
                        // 如果找不到容器，使用简单的alert
                        alert('自己不能邀请自己');
                        return;
                    }
                    
                    // 移除现有的错误提示
                    const existingError = document.querySelector('.self-invite-error');
                    if (existingError) {
                        existingError.remove();
                    }
                    
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'self-invite-error';
                    messageDiv.innerHTML = `
                        <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #e74c3c88 0%, #e74c3ccc 100%); border-radius: 15px; margin-bottom: 20px; color: white;">
                            <div style="font-size: 20px; font-weight: 600; margin-bottom: 10px;">
                                ⚠️ 操作提醒
                            </div>
                            <div style="font-size: 16px; margin-bottom: 15px; opacity: 0.9;">
                                自己不能邀请自己
                            </div>
                            <div style="font-size: 14px; opacity: 0.8; margin-bottom: 15px;">
                                请检查邀请链接是否正确，或联系邀请人重新发送邀请
                            </div>
                            <button onclick="this.parentElement.parentElement.remove()" style="background: white; color: #e74c3c; border: none; padding: 10px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer;">
                                我知道了
                            </button>
                        </div>
                    `;
                    
                    // 插入到header后面
                    const header = container.querySelector('.header');
                    if (header) {
                        header.insertAdjacentElement('afterend', messageDiv);
                    } else {
                        container.insertBefore(messageDiv, container.firstChild);
                    }
                    
                    console.log('自己邀请自己错误提示显示成功');
                } catch (error) {
                    console.error('显示自己邀请自己错误提示失败:', error);
                    // 如果出错，使用简单的alert作为备选
                    alert('自己不能邀请自己');
                }
            }

            // 显示注册成功消息（注册成功但flag=N时使用）
            showRegistrationSuccessMessage() {
                try {
                    console.log('🎉 显示注册成功消息');
                    
                    const container = document.querySelector('.container');
                    if (!container) {
                        console.error('找不到容器元素');
                        return;
                    }
                    
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'registration-success-message';
                    messageDiv.innerHTML = `
                        <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #28a74588 0%, #28a745cc 100%); border-radius: 15px; margin-bottom: 20px; color: white;">
                            <div style="font-size: 20px; font-weight: 600; margin-bottom: 10px;">
                                🎉 注册成功！
                            </div>
                            <div style="font-size: 14px; margin-bottom: 15px; opacity: 0.9;">
                                恭喜您成功注册账号，可以开始使用平台功能了
                            </div>
                            <div style="font-size: 12px; opacity: 0.8;">
                                ${this.buyerId ? `买家ID: ${this.buyerId}` : ''}
                                ${this.storedOpenid ? `微信ID: ${this.storedOpenid}` : ''}
                            </div>
                        </div>
                    `;
                    
                    // 插入到header后面
                    const header = container.querySelector('.header');
                    if (header) {
                        header.insertAdjacentElement('afterend', messageDiv);
                    } else {
                        container.insertBefore(messageDiv, container.firstChild);
                    }
                    
                    // 隐藏注册表单
                    const form = document.getElementById('registerForm');
                    const terms = document.querySelector('.terms');
                    const testSection = document.querySelector('.test-section');
                    if (form) form.style.display = 'none';
                    if (terms) terms.style.display = 'none';
                    if (testSection) testSection.style.display = 'none';
                    
                    console.log('注册成功消息显示成功');
                } catch (error) {
                    console.error('显示注册成功消息失败:', error);
                }
            }

            // 解析URL参数
            parseUrlParams() {
                try {
                    console.log('🔍 开始解析URL参数...');
                    console.log('📍 完整URL:', window.location.href);
                    console.log('📍 搜索参数:', window.location.search);
                    
                    let urlParams = new URLSearchParams(window.location.search);
                    
                    // 处理嵌套的 redirect 参数
                    const redirectParam = urlParams.get('redirect');
                    if (redirectParam) {
                        console.log('📋 发现redirect参数，尝试解析嵌套URL...');
                        try {
                            // 解码 redirect 参数
                            const decodedRedirect = decodeURIComponent(redirectParam);
                            console.log('📋 解码后的redirect:', decodedRedirect);
                            
                            // 如果 redirect 参数本身包含 URL 参数，尝试解析
                            if (decodedRedirect.includes('?')) {
                                const redirectUrl = new URL(decodedRedirect, window.location.origin);
                                const redirectParams = new URLSearchParams(redirectUrl.search);
                                
                                // 合并参数，优先使用 redirect 中的参数
                                const mergedParams = new URLSearchParams();
                                
                                // 首先添加当前 URL 的参数
                                urlParams.forEach((value, key) => {
                                    if (key !== 'redirect') {
                                        mergedParams.append(key, value);
                                    }
                                });
                                
                                // 然后添加 redirect URL 中的参数
                                redirectParams.forEach((value, key) => {
                                    mergedParams.set(key, value); // 使用 set 覆盖同名参数
                                });
                                
                                urlParams = mergedParams;
                                console.log('📋 合并后的参数:', mergedParams.toString());
                            }
                        } catch (error) {
                            console.warn('解析redirect参数失败:', error);
                        }
                    }
                    
                    // 解析buserid (原来的buyerid)
                    const buserid = urlParams.get('buserid');
                    if (buserid) {
                        this.buyerId = buserid.trim();
                        console.log('✅ 从URL解析到buserid:', this.buyerId);
                    } else {
                        console.log('❌ URL中未找到buserid参数');
                    }
                    
                    // 解析muserid (原来的openid)
                    const muserid = urlParams.get('muserid');
                    const openid = urlParams.get('openid'); // 也尝试解析 openid
                    if (muserid) {
                        this.storedOpenid = muserid.trim();
                        console.log('✅ 从URL解析到muserid:', this.storedOpenid);
                    } else if (openid) {
                        this.storedOpenid = openid.trim();
                        console.log('✅ 从URL解析到openid:', this.storedOpenid);
                    } else {
                        console.log('❌ URL中未找到muserid或openid参数');
                    }
                    
                    // 解析flag参数
                    const flag = urlParams.get('flag');
                    if (flag) {
                        this.flag = flag.trim().toUpperCase();
                        console.log('✅ 从URL解析到flag:', this.flag);
                    } else {
                        console.log('❌ URL中未找到flag参数');
                        // 如果没有flag参数，设置默认值
                        this.flag = 'N';
                        console.log('📝 设置默认flag值为N');
                    }
                    
                    // 解析auto_login参数
                    const autoLogin = urlParams.get('auto_login');
                    if (autoLogin) {
                        console.log('✅ 从URL解析到auto_login:', autoLogin);
                    }
                    
                    console.log('📋 最终解析结果:');
                    console.log('- buyerId:', this.buyerId);
                    console.log('- storedOpenid:', this.storedOpenid);
                    console.log('- flag:', this.flag);
                    
                } catch (error) {
                    console.error('❌ 解析URL参数失败:', error);
                }
            }

            handlePhoneInput(e) {
                const value = e.target.value.replace(/\D/g, '');
                e.target.value = value;
                
                const phoneError = document.getElementById('phoneError');
                const phoneSuccess = document.getElementById('phoneSuccess');
                
                if (value.length === 0) {
                    this.clearValidation(e.target);
                    this.verificationSection.style.display = 'none';
                    this.phoneDisplay.style.display = 'none';
                    this.submitBtn.disabled = true;
                    return;
                }
                
                if (value.length === 11) {
                    if (this.validatePhone(value)) {
                        this.showSuccess(e.target, '手机号格式正确');
                        this.verificationSection.style.display = 'block';
                        this.phoneDisplay.style.display = 'block';
                        this.phoneDisplay.textContent = `验证码将发送至: ${value}`;
                        this.checkFormValidity();
                    } else {
                        this.showError(e.target, '请输入正确的手机号码');
                        this.verificationSection.style.display = 'none';
                        this.phoneDisplay.style.display = 'none';
                        this.submitBtn.disabled = true;
                    }
                } else {
                    this.clearValidation(e.target);
                    this.verificationSection.style.display = 'none';
                    this.phoneDisplay.style.display = 'none';
                    this.submitBtn.disabled = true;
                }
            }

            handleCodeInput(e) {
                const value = e.target.value.replace(/\D/g, '');
                e.target.value = value;
                
                if (value.length === 0) {
                    this.clearValidation(e.target);
                } else if (value.length === 6) {
                    this.showSuccess(e.target, '验证码格式正确');
                } else {
                    this.clearValidation(e.target);
                }
                
                this.checkFormValidity();
            }

            handleNameInput(e) {
                const value = e.target.value.trim();
                
                if (value.length === 0) {
                    this.clearValidation(e.target);
                } else if (value.length >= 2) {
                    this.showSuccess(e.target, '姓名格式正确');
                } else {
                    this.clearValidation(e.target);
                }
                
                this.checkFormValidity();
            }

            handleCompanyInput(e) {
                const value = e.target.value.trim();
                
                if (value.length === 0) {
                    this.clearValidation(e.target);
                } else if (value.length >= 2) {
                    this.showSuccess(e.target, '公司名称格式正确');
                } else {
                    this.clearValidation(e.target);
                }
                
                this.checkFormValidity();
            }

            validatePhone(phone) {
                const regex = /^1[3-9]\d{9}$/;
                return regex.test(phone);
            }

            showError(input, message) {
                input.classList.add('error');
                input.classList.remove('success');
                const errorElement = document.getElementById(input.name + 'Error');
                const successElement = document.getElementById(input.name + 'Success');
                
                if (errorElement) {
                    errorElement.textContent = message;
                    errorElement.style.display = 'block';
                }
                if (successElement) {
                    successElement.style.display = 'none';
                }
                
                // 如果找不到对应的错误显示元素，使用通用方式显示错误
                if (!errorElement) {
                    console.warn('找不到错误显示元素:', input.name + 'Error');
                    alert(message);
                }
            }

            showSuccess(input, message) {
                input.classList.add('success');
                input.classList.remove('error');
                const errorElement = document.getElementById(input.name + 'Error');
                const successElement = document.getElementById(input.name + 'Success');
                
                if (successElement) {
                    successElement.textContent = message;
                    successElement.style.display = 'block';
                }
                if (errorElement) {
                    errorElement.style.display = 'none';
                }
                
                // 如果找不到对应的成功显示元素，仅记录日志
                if (!successElement) {
                    console.warn('找不到成功显示元素:', input.name + 'Success');
                }
            }

            clearValidation(input) {
                input.classList.remove('error', 'success');
                const errorElement = document.getElementById(input.name + 'Error');
                const successElement = document.getElementById(input.name + 'Success');
                errorElement.style.display = 'none';
                successElement.style.display = 'none';
            }

            checkFormValidity() {
                const name = document.getElementById('name').value;
                const company = document.getElementById('company').value;
                const phone = this.phoneInput.value;
                const code = this.verificationInput.value;
                
                if (name && company && phone.length === 11 && this.validatePhone(phone) && code.length === 6) {
                    this.submitBtn.disabled = false;
                } else {
                    this.submitBtn.disabled = true;
                }
            }

            sendVerificationCodeNew(event) {
                console.log('🚀 sendVerificationCode 开始执行');
                
                // 阻止默认行为
                if (event) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                
                const phone = this.phoneInput.value;
                console.log('📱 手机号:', phone);
                
                if (!this.validatePhone(phone)) {
                    console.log('❌ 手机号格式不正确');
                    this.showError(this.phoneInput, '请输入正确的手机号码');
                    return false;
                }

                this.sendCodeBtn.disabled = true;
                this.startCountdown();

                // 使用Promise处理异步调用
                this.sendSmsCode(phone)
                    .then(result => {
                        console.log('📨 API响应结果:', result);
                        
                        if (result && result.success) {
                            console.log('✅ 验证码发送成功');
                            this.showSuccess(this.verificationInput, '验证码已发送');
                        } else {
                            console.log('❌ 验证码发送失败:', result ? result.message : '未知错误');
                            this.showError(this.verificationInput, (result && result.message) || '发送失败');
                            this.sendCodeBtn.disabled = false;
                            this.stopCountdown();
                        }
                    })
                    .catch(error => {
                        console.error('❌ 发送验证码失败:', error);
                        this.showError(this.verificationInput, error.message || '发送失败，请重试');
                        this.sendCodeBtn.disabled = false;
                        this.stopCountdown();
                    });
                
                console.log('🏁 sendVerificationCodeNew 执行完成');
                return false;
            }

  
            
            // 发送短信验证码 - 使用新的API客户端
            async sendSmsCode(phone) {
                try {
                    console.log('📞 调用 businessApi.sendSmsCode...');
                    console.log('📞 传递的手机号:', phone);
                    
                    const result = await window.businessApi.sendSmsCode(phone);
                    
                    console.log('📞 businessApi 返回结果:', result);
                    return result;
                } catch (error) {
                    console.error('❌ 发送验证码失败:', error);
                    throw error;
                }
            }

            // 提交注册 - 使用新的API客户端
            async submitRegister(data) {
                try {
                    const result = await window.businessApi.register(data);
                    return result;
                } catch (error) {
                    console.error('注册失败:', error);
                    throw error;
                }
            }

            startCountdown() {
                this.countdown = 60;
                this.sendCodeBtn.textContent = `${this.countdown}秒`;
                
                this.timer = setInterval(() => {
                    this.countdown--;
                    this.sendCodeBtn.textContent = `${this.countdown}秒`;
                    
                    if (this.countdown <= 0) {
                        this.stopCountdown();
                    }
                }, 1000);
            }

            stopCountdown() {
                if (this.timer) {
                    clearInterval(this.timer);
                    this.timer = null;
                }
                this.sendCodeBtn.disabled = false;
                this.sendCodeBtn.textContent = '重新获取';
            }

            async handleSubmitNew(e) {
                e.preventDefault();
                
                const name = document.getElementById('name').value;
                const company = document.getElementById('company').value;
                const phone = this.phoneInput.value;
                const code = this.verificationInput.value;
                
                if (!this.validatePhone(phone) || code.length !== 6 || !name || !company) {
                    return;
                }

                this.showLoading(true);
                this.submitBtn.disabled = true;

                try {
                    // 检查muserid和buserid是否相同，如果相同则阻止提交
                    console.log('📋 检查用户ID:');
                    console.log('- storedOpenid (muserid):', this.storedOpenid);
                    console.log('- buyerId (buserid):', this.buyerId);
                    
                    if (this.storedOpenid && this.buyerId && this.storedOpenid === this.buyerId) {
                        console.log('⚠️ muserid和buserid相同，阻止提交');
                        this.showSelfInviteError();
                        this.showLoading(false);
                        this.submitBtn.disabled = false;
                        return;
                    }
                    
                    // 构建注册数据，匹配后端接口字段
                    const registerData = {
                        realname: name,
                        companyname: company,
                        mobile: phone,
                        captcha: code
                    };
                    
                    // 如果有保存的openid，添加到注册数据中
                    if (this.storedOpenid) {
                        registerData.muserid = this.storedOpenid;
                    }
                    
                    // 如果有buyerid，添加到注册数据中
                    if (this.buyerId) {
                        registerData.buserid = this.buyerId;
                    }
                    
                    // 调用后端API提交注册
                    const result = await this.submitRegister(registerData);
                    
                    if (result.success) {
                        alert('注册成功！');
                        
                        // 设置用户认证状态
                        const userData = {
                            muserid: this.storedOpenid,
                            buserid: this.buyerId,
                            flag: this.flag,
                            name: name,
                            company: company,
                            phone: phone
                        };
                        
                        if (window.authManager) {
                            window.authManager.setAuth(userData);
                        }
                        
                        // 注册成功后不进行任何重定向，只显示成功消息
                        console.log('✅ 注册成功，保持在当前页面');
                        this.showRegistrationSuccessMessage();
                        
                        this.form.reset();
                        this.resetForm();
                    } else {
                        throw new Error(result.message || '注册失败');
                    }
                    
                } catch (error) {
                    this.showError(this.verificationInput, error.message || '验证码错误或注册失败');
                    this.submitBtn.disabled = false;
                } finally {
                    this.showLoading(false);
                }
            }

  
            showLoading(show) {
                this.loading.style.display = show ? 'block' : 'none';
            }

              showAutoLoginMessage() {
                try {
                    // 在页面上显示自动登录跳转提示
                    const container = document.querySelector('.container');
                    if (!container) {
                        console.error('找不到容器元素');
                        return;
                    }
                    
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'auto-login-message';
                    messageDiv.innerHTML = `
                        <div style="text-align: center; padding: 20px; background: #e8f5e8; border-radius: 10px; margin-bottom: 20px;">
                            <div style="color: #27ae60; font-size: 16px; font-weight: 500; margin-bottom: 8px;">
                                🎉 检测到您已注册
                            </div>
                            <div style="color: #666; font-size: 14px; margin-bottom: 15px;">
                                正在为您自动跳转到个人中心...
                            </div>
                            <div style="margin-top: 12px;">
                                <div class="spinner" style="border-color: #27ae60; border-top-color: transparent; width: 20px; height: 20px;"></div>
                            </div>
                            <div style="margin-top: 15px;">
                                <button onclick="forceRedirect()" style="background: #28a745; color: white; border: none; padding: 8px 16px; border-radius: 5px; font-size: 12px; cursor: pointer;">
                                    立即跳转
                                </button>
                            </div>
                        </div>
                    `;
                    
                    // 插入到header后面
                    const header = container.querySelector('.header');
                    if (header) {
                        header.insertAdjacentElement('afterend', messageDiv);
                    } else {
                        container.insertBefore(messageDiv, container.firstChild);
                    }
                    
                    // 隐藏注册表单
                    const form = document.getElementById('registerForm');
                    const terms = document.querySelector('.terms');
                    const testSection = document.querySelector('.test-section');
                    if (form) form.style.display = 'none';
                    if (terms) terms.style.display = 'none';
                    if (testSection) testSection.style.display = 'none';
                    
                    console.log('自动登录消息显示成功');
                } catch (error) {
                    console.error('显示自动登录消息失败:', error);
                }
            }

  
            resetForm() {
                this.verificationSection.style.display = 'none';
                this.phoneDisplay.style.display = 'none';
                this.submitBtn.disabled = true;
                this.stopCountdown();
                this.clearValidation(this.phoneInput);
                this.clearValidation(this.verificationInput);
            }

            // 强制跳转到个人中心（用于解决卡住的问题）
            forceRedirectToProfile() {
                console.log('强制跳转到个人中心');
                console.log('当前存储的参数:');
                console.log('- muserid:', this.storedOpenid);
                console.log('- buserid:', this.buyerId);
                console.log('- flag:', this.flag);
                
                const profileUrl = 'profile.html';
                const params = new URLSearchParams();
                
                // 添加当前存储的参数
                if (this.storedOpenid) {
                    params.append('muserid', this.storedOpenid);
                }
                if (this.buyerId) {
                    params.append('buserid', this.buyerId);
                }
                if (this.flag) {
                    params.append('flag', this.flag);
                }
                
                // 添加强制跳转标识
                params.append('force_redirect', 'true');
                params.append('timestamp', Date.now());
                
                const fullUrl = `${profileUrl}?${params.toString()}`;
                
                console.log('强制跳转URL:', fullUrl);
                
                try {
                    window.location.href = fullUrl;
                } catch (error) {
                    console.error('强制跳转失败:', error);
                    window.open(fullUrl, '_self');
                }
            }

            // 测试跳转到个人中心
            testRedirectToProfile() {
                console.log('测试跳转到个人中心');
                console.log('当前存储的参数:');
                console.log('- muserid:', this.storedOpenid);
                console.log('- buserid:', this.buyerId);
                console.log('- flag:', this.flag);
                
                const profileUrl = 'profile.html';
                const params = new URLSearchParams();
                
                // 添加当前存储的参数
                if (this.storedOpenid) {
                    params.append('muserid', this.storedOpenid);
                }
                if (this.buyerId) {
                    params.append('buserid', this.buyerId);
                }
                if (this.flag) {
                    params.append('flag', this.flag);
                }
                
                // 添加测试标识
                params.append('test', 'manual_redirect');
                params.append('timestamp', Date.now());
                
                // 如果表单有数据，也添加到参数中
                const name = document.getElementById('name').value;
                const company = document.getElementById('company').value;
                const phone = this.phoneInput.value;
                
                if (name) params.append('name', encodeURIComponent(name));
                if (company) params.append('company', encodeURIComponent(company));
                if (phone) params.append('phone', encodeURIComponent(phone));
                
                const fullUrl = `${profileUrl}?${params.toString()}`;
                
                console.log('跳转URL:', fullUrl);
                
                // 显示跳转确认
                const confirmJump = confirm('即将跳转到个人中心页面进行测试\n\n跳转URL：' + fullUrl + '\n\n是否继续？');
                
                if (confirmJump) {
                    window.location.href = fullUrl;
                }
            }
        }

        // 取消默认跳转
        function cancelRedirect() {
            console.log('用户取消默认跳转');
            const registerInstance = window.phoneRegisterInstance;
            if (registerInstance) {
                // 显示注册表单
                const form = document.getElementById('registerForm');
                const terms = document.querySelector('.terms');
                const testSection = document.querySelector('.test-section');
                const redirectMessage = document.querySelector('.default-redirect-message');
                
                if (form) form.style.display = 'block';
                if (terms) terms.style.display = 'block';
                if (testSection) testSection.style.display = 'block';
                if (redirectMessage) redirectMessage.style.display = 'none';
                
                console.log('取消跳转，显示注册表单');
            }
        }

        // 强制跳转到个人中心（用于解决卡住的问题）
        function forceRedirect() {
            console.log('用户点击强制跳转');
            const registerInstance = window.phoneRegisterInstance;
            if (registerInstance) {
                registerInstance.forceRedirectToProfile();
            } else {
                // 如果实例不存在，直接跳转
                const profileUrl = 'profile.html';
                const params = new URLSearchParams();
                params.append('force_redirect', 'true');
                params.append('timestamp', Date.now());
                
                const fullUrl = `${profileUrl}?${params.toString()}`;
                console.log('强制跳转到:', fullUrl);
                window.location.href = fullUrl;
            }
        }

        // 测试跳转到个人中心功能
        function testRedirectToProfile() {
            const registerInstance = window.phoneRegisterInstance;
            if (registerInstance) {
                registerInstance.testRedirectToProfile();
            } else {
                // 如果实例不存在，直接跳转
                const profileUrl = 'profile.html';
                const params = new URLSearchParams();
                params.append('test', 'manual_redirect');
                params.append('timestamp', Date.now());
                
                const fullUrl = `${profileUrl}?${params.toString()}`;
                console.log('测试跳转到:', fullUrl);
                window.location.href = fullUrl;
            }
        }

        // 跳转到个人中心
        function goToProfile() {
            console.log('跳转到个人中心');
            const profileUrl = 'profile.html';
            
            // 获取当前实例中的用户数据
            const registerInstance = window.phoneRegisterInstance;
            const params = new URLSearchParams();
            
            if (registerInstance) {
                // 只添加buserid参数（根据要求）
                if (registerInstance.buyerId) {
                    params.append('buserid', registerInstance.buyerId);
                }
            }
            
            // 添加来源标识
            params.append('from', 'register');
            params.append('timestamp', Date.now());
            
            const fullUrl = `${profileUrl}?${params.toString()}`;
            console.log('跳转到个人中心:', fullUrl);
            
            // 显示跳转确认
            const confirmJump = confirm('即将跳转到个人中心\n\n是否继续？');
            
            if (confirmJump) {
                window.location.href = fullUrl;
            }
        }

        // 调试参数函数
        function debugParams() {
            console.log('🔍 调试当前参数状态');
            if (window.phoneRegisterInstance) {
                console.log('📋 PhoneRegister实例参数:');
                console.log('- flag:', window.phoneRegisterInstance.flag);
                console.log('- buyerId:', window.phoneRegisterInstance.buyerId);
                console.log('- storedOpenid:', window.phoneRegisterInstance.storedOpenid);
                console.log('- 当前URL:', window.location.href);
                
                alert(`当前参数状态:\nflag: ${window.phoneRegisterInstance.flag}\nbuyerId: ${window.phoneRegisterInstance.buyerId}\nstoredOpenid: ${window.phoneRegisterInstance.storedOpenid}\nURL: ${window.location.href}`);
            } else {
                console.log('❌ PhoneRegister实例不存在');
                alert('PhoneRegister实例不存在');
            }
        }

        // 初始化注册页面
        document.addEventListener('DOMContentLoaded', () => {
            console.log('🌟 DOM内容已加载，开始初始化PhoneRegister');
            const instance = new PhoneRegister();
            window.phoneRegisterInstance = instance; // 保存实例供测试使用
            console.log('📱 PhoneRegister实例已创建并保存到全局变量');
            
            // 更新当前buserid显示
            updateCurrentBuyerIdDisplay();
        });

        // 更新当前buserid显示
        function updateCurrentBuyerIdDisplay() {
            const currentBuyerIdElement = document.getElementById('currentBuyerId');
            if (currentBuyerIdElement) {
                // 尝试从URL参数获取buserid和flag
                const urlParams = new URLSearchParams(window.location.search);
                const buserid = urlParams.get('buserid');
                const flag = urlParams.get('flag');
                
                if (buserid && flag) {
                    currentBuyerIdElement.textContent = `${buserid} (Flag: ${flag})`;
                } else if (buserid) {
                    currentBuyerIdElement.textContent = `${buserid} (Flag: 未设置)`;
                } else {
                    // 尝试从注册实例获取
                    const registerInstance = window.phoneRegisterInstance;
                    if (registerInstance && registerInstance.buyerId) {
                        const displayFlag = registerInstance.flag || '未设置';
                        currentBuyerIdElement.textContent = `${registerInstance.buyerId} (Flag: ${displayFlag})`;
                    } else {
                        currentBuyerIdElement.textContent = '未设置';
                    }
                }
            }
        }
    </script>
</body>
</html>